package com.whfc.fuum.service.impl;

import com.alibaba.fastjson.JSON;
import com.whfc.common.exception.BizException;
import com.whfc.common.weixin.bean.WxAccessToken;
import com.whfc.common.weixin.mp.TokenApi;
import com.whfc.fuum.dao.WxConfigMapper;
import com.whfc.fuum.dto.WxConfigDTO;
import com.whfc.fuum.redis.WxTokenRedisDao;
import com.whfc.fuum.service.WxConfigService;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description:
 * @author: xugcheng
 * @version: 1.0
 * @date: 2020-12-15 10:58
 */
@DubboService(interfaceClass = WxConfigService.class, version = "1.0.0")
public class WxConfigServiceImpl implements WxConfigService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private static Map<String, WxConfigDTO> configDTOMap = new ConcurrentHashMap<>();

    @Autowired
    private WxConfigMapper wxConfigMapper;

    @Autowired
    private WxTokenRedisDao wxTokenRedisDao;

    @Override
    public WxConfigDTO getWxConfig(String appType, boolean refresh) throws BizException {
        logger.info("获取微信配置,appType:{},refresh:{}", appType, refresh);
        appType = appType.toLowerCase();
        WxConfigDTO configDTO = configDTOMap.get(appType);
        if (configDTO == null || refresh) {
            configDTO = wxConfigMapper.selectConfigByAppType(appType);
            if (configDTO != null) {
                configDTOMap.put(appType, configDTO);
            }
        }
        return configDTO;
    }

    @Override
    public void refreshAccessToken(String appType) throws BizException {
        logger.info("刷新accessToken,appType:{}", appType);
        WxConfigDTO wxConfigDTO = wxConfigMapper.selectConfigByAppType(appType);
        if (wxConfigDTO != null) {
            String appId = wxConfigDTO.getAppId();
            String secret = wxConfigDTO.getAppSecret();
            String result = TokenApi.getAccessToken(appId, secret);
            WxAccessToken token = JSON.parseObject(result, WxAccessToken.class);
            if (token != null && !StringUtils.isEmpty(token.getAccessToken())) {
                wxTokenRedisDao.setAccessToken(appType, token.getAccessToken(), token.getExpiresIn());
            }
        }
    }

    @Override
    public String getAccessToken(String appType) throws BizException {
        logger.info("获取accessToken,appType:{}", appType);
        String accessToken = wxTokenRedisDao.getAccessToken(appType);
        return accessToken;
    }
}
